﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "login/logindlg.h"
#include "CommUtil/common.h"
#include<QMessageBox>
#include <QDebug>
#include<Qdir>
#include<Windows.h>

extern MainWindow* g_pMainwindow;
extern CLoginDlg*  g_pLoginDlg;

MainWindow::MainWindow()
{
    //成员变量初始化
    m_CZCEInstrumentMap.clear();
    m_SHFEInstrumentMap.clear();
    m_CFFEXInstrumentMap.clear();
    m_DCEInstrumentMap.clear();
    m_lInstrumentCount = 0;
	m_pmdUserApi = NULL;
	m_pTradeUserApi = NULL;
	m_pThostFtdcMdSpiImpl = NULL;
	m_pThostFtdcTraderSpiImpl = NULL;

	//读取Config.ini文件
	ReadConfigFile();

    setupViews();
    //statusBar();
    setWindowTitle(QStringLiteral("交易宝"));

    setMouseTracking(true);
    m_pStatus = new QStatusBar();
    setStatusBar(m_pStatus);

    createActions();
    createMenus();
}

MainWindow::~MainWindow()
{
}

void MainWindow::setupViews()
{
    marketselfwidget = new MarketSelfWidget;
    marketcomexch = new MarketComexch;
    popmktcombineexch = new PopMktCombineExch;

    m_Quottab = new QTabWidget;
    m_Quottab->addTab(marketselfwidget,QStringLiteral("自选行情"));
    m_Quottab->addTab(marketcomexch,QStringLiteral("自定义组合行情"));

    m_ControlDlg = new QDialog;
    m_SingleControlDlg = new SingleControlDialog;
    m_CombineControlDlg = new CombineControlDialog;
    mainorderwidget = new MainOrderWidget;
    mainpreentrustwidget = new MainPreEntrustWidget;
    mainconditionwidget = new MainConditionWidget;
    maincombineentrustwidget = new MainCombineEntrustWidget;
    mainbalancewidget = new MainBalanceWidget;
    mainholdwidget = new MainHoldWidget;
    mainentrustqueryhiswidget = new MainEntrustQueryHisWidget;
    mainbusinessqueryhiswidget = new MainBusinessQueryHisWidget;
    maincontractwidget = new MainContractWidget;
    mainaverageentrustwidget = new MainAverageEntrustWidget;
    m_SettlementInfoDialog   = new SettlementInfoDialog;//客户结算单确认Dialog

    m_tabWidget = new QTabWidget;
    m_tabWidget->addTab(mainorderwidget,QStringLiteral("委托"));
    m_tabWidget->addTab(mainpreentrustwidget,QStringLiteral("预埋单"));
    m_tabWidget->addTab(mainconditionwidget,QStringLiteral("条件单"));
    m_tabWidget->addTab(maincombineentrustwidget,QStringLiteral("组合单"));
    m_tabWidget->addTab(mainbalancewidget,QStringLiteral("资金"));
    m_tabWidget->addTab(mainholdwidget,QStringLiteral("持仓"));
    m_tabWidget->addTab(mainentrustqueryhiswidget,QStringLiteral("查委托"));
    m_tabWidget->addTab(mainbusinessqueryhiswidget,QStringLiteral("查成交"));
    m_tabWidget->addTab(maincontractwidget,QStringLiteral("合约查询"));
    //tabWidget2->addTab(mainaverageentrustwidget,QStringLiteral("均价下单"));

    QGridLayout* hlayout = new QGridLayout;
    hlayout->addWidget(m_Quottab,0,0,1,7);
    hlayout->addWidget(m_SingleControlDlg,1,0,1,2);
    hlayout->addWidget(m_CombineControlDlg,1,0,1,2);
    hlayout->addWidget(m_tabWidget,1,2,1,5);

    m_ControlDlg = m_SingleControlDlg;
    m_CombineControlDlg->hide();

    QWidget* mainwidget = new QWidget;
    mainwidget->setLayout(hlayout);
    setCentralWidget(mainwidget);

    ///选择自选行情和自定义组合行情时 切换控制模块
    connect(marketselfwidget->m_tableView, SIGNAL(clicked(const QModelIndex &)), this, SLOT(SelectSelfContract(const QModelIndex &)));
    connect(marketcomexch->m_tableView, SIGNAL(clicked(const QModelIndex &)), this, SLOT(SelectCombContract(const QModelIndex &)));

    ///报单请求事件关联
    connect(this->m_SingleControlDlg,SIGNAL(OnOrderInsert(CThostFtdcInputOrderField*)),this,SLOT(OnOrderInsert(CThostFtdcInputOrderField*)));
    connect(this->mainholdwidget,SIGNAL(OnOrderInsert(CThostFtdcInputOrderField*)),this,SLOT(OnOrderInsert(CThostFtdcInputOrderField*)));
    ///预埋单请求事件关联
    connect(this->m_SingleControlDlg,SIGNAL(OnParkedOrderInsert(CThostFtdcParkedOrderField*)),this,SLOT(OnParkedOrderInsert(CThostFtdcParkedOrderField*)));
    ///条件单请求事件关联
    connect(this->m_SingleControlDlg,SIGNAL(OnConditonOrderInsert(CThostFtdcInputOrderField*,ConditionType*)),this,SLOT(OnConditonOrderInsert(CThostFtdcInputOrderField*,ConditionType*)));

    ///资金账户查询事件关联
	connect(this->mainbalancewidget,SIGNAL(ReqQryTradingAccount(QString)),this,SLOT(ReqQryTradingAccount(QString)));
    ///持仓查询事件关联
    connect(this->mainholdwidget,SIGNAL(ReqQryInvestorPosition(QString)),this,SLOT(ReqQryInvestorPosition(QString)));
    ///查委托事件关联
    connect(this->mainentrustqueryhiswidget,SIGNAL(QueryOrder(QStringList)),this,SLOT(QueryOrder(QStringList)));
    ///查成交事件关联
    connect(this->mainbusinessqueryhiswidget,SIGNAL(ReqQryTrade(QString)),this,SLOT(ReqQryTrade(QString)));
    ///撤销委托事件关联
    connect(this->mainorderwidget,SIGNAL(SigDeleteOrder(QString)),this,SLOT(DeleteOrder(QString)));
    ///撤销全部委托事件关联
    connect(this->mainorderwidget,SIGNAL(SigDeleteAllOrders()),this,SLOT(DeleteAllOrders()));

	//删除预埋单事件关联
	connect(this->mainpreentrustwidget,SIGNAL(SigRemoveParkedOrder(CThostFtdcRemoveParkedOrderField*)),this,SLOT(RemoveParkedOrder(CThostFtdcRemoveParkedOrderField*)));

	//组合单事件关联
	connect(this->m_CombineControlDlg,SIGNAL(NewCombineOrder(COMBINORDERINFO)),this,SLOT( AddNewCombineOrder(COMBINORDERINFO )));
	//组合行情推送 与 组合单关联
	connect(this->marketcomexch,SIGNAL(SigCombineOrder(QString,QString,int,QString,int,QString)),this,SLOT(SlotCombineOrder(QString,QString,int,QString,int,QString)));

    //均价单事件关联
    connect(this->mainaverageentrustwidget,SIGNAL(NewAverageOrder(AVERAGEORDERINFO)),this,SLOT(AddNewAverageOrder(AVERAGEORDERINFO)));
	connect(this->mainaverageentrustwidget,SIGNAL(OnOrderInsert(CThostFtdcInputOrderField*,QString )),this,SLOT(OnOrderInsert(CThostFtdcInputOrderField*,QString )));

    connect(m_Quottab,SIGNAL(tabBarDoubleClicked(int)),this,SLOT(QuotTabDoubleClicked(int)));
}
//创建Actions
void MainWindow::createActions()
{
    newAct=new QAction(QStringLiteral("&退出"),this);
    newAct->setShortcut(QKeySequence("X"));//设置快捷键
    newAct->setStatusTip(QStringLiteral("退出"));//设置状态栏提示

    newAct1=new QAction(QStringLiteral("&自选行情设置"),this);
    newAct1->setStatusTip(QStringLiteral("自选行情设置"));//设置状态栏提示

    newAct2=new QAction(QStringLiteral("&自定义组合行情"),this);
    newAct2->setStatusTip(QStringLiteral("自定义组合行情"));//设置状态栏提示

    newAct3=new QAction(QStringLiteral("&交易所组合行情"),this);
    newAct3->setStatusTip(QStringLiteral("交易所组合行情"));//设置状态栏提示

    newAct4=new QAction(QStringLiteral("&默认下单量设置"),this);
    newAct4->setStatusTip(QStringLiteral("默认下单量设置"));//设置状态栏提示

    newAct5=new QAction(QStringLiteral("&快速下单设置"),this);
    newAct5->setStatusTip(QStringLiteral("快速下单设置"));//设置状态栏提示

    newAct6=new QAction(QStringLiteral("&组合单参数设置"),this);
    newAct6->setStatusTip(QStringLiteral("组合单参数设置"));//设置状态栏提示

    aboutAct1=new QAction(QStringLiteral("&打开帮助文档"),this);
    aboutAct1->setStatusTip(QStringLiteral("打开帮助文档"));

    aboutAct2=new QAction(QStringLiteral("&中粮基金通投资指导端"),this);
    aboutAct2->setStatusTip(QStringLiteral("中粮基金通投资指导端"));

    //策略应用
    m_StrategyAct = new QAction(QStringLiteral("&日内交易策略"),this);
    m_StrategyAct->setStatusTip(QStringLiteral("日内交易策略应用"));

}
void MainWindow::createMenus()
{
    //文件菜单
    fileMenu = menuBar()->addMenu(QStringLiteral("&文件(F)"));
    fileMenu->addAction(newAct);//退出

    editMenu = menuBar()->addMenu(QStringLiteral("&系统(S)"));
    editMenu->addAction(newAct1);
    editMenu->addAction(newAct2);
    //editMenu->addAction(newAct3);
    //editMenu->addAction(newAct4);
    //editMenu->addAction(newAct5);
    //editMenu->addAction(newAct6);

    //策略菜单
    m_strategyMenu = menuBar()->addMenu(QStringLiteral("&策略应用(T)"));
    m_strategyMenu->addAction(m_StrategyAct);

    //帮助菜单
    helpMenu = menuBar()->addMenu(QStringLiteral("&帮助(H)"));
    helpMenu->addAction(aboutAct1);
    helpMenu->addAction(aboutAct2);

    connect(newAct, SIGNAL(triggered()), this, SLOT(exit()));
    connect(newAct1, SIGNAL(triggered()), this, SLOT(selfdialogshow()));
    connect(newAct2, SIGNAL(triggered()), this, SLOT(marketcomexchdialogshow()));
    connect(m_StrategyAct,SIGNAL(triggered()),this,SLOT(ShowStrategyTab()));
    //connect(newAct3, SIGNAL(triggered()), this, SLOT(combineexchdialogshow()));
    //connect(newAct4, SIGNAL(triggered()), this, SLOT(defaultorderdialogshow()));
    //connect(newAct5, SIGNAL(triggered()), this, SLOT(quickorderdialogshow()));
    //connect(newAct6, SIGNAL(triggered()), this, SLOT(combineorderdialogshow()));
    connect(this,SIGNAL(SigSetStatusTip(QString)),this,SLOT(SetStatusTip(QString)));
	connect(this,SIGNAL(SigShowSettlementInfoDialog()),this,SLOT(SlotShowSettlementInfoDialog()));
}
//交易者结算单确认
void MainWindow::SlotShowSettlementInfoDialog(){
	int iRet = this->m_SettlementInfoDialog->exec();
    if(1 == iRet){
        //点击确认按钮
        //投资者结算结果确认
        CThostFtdcSettlementInfoConfirmField qrySettlementInfo;
        QString Time = QTime::currentTime().toString("hh:mm:ss");

        strncpy_s(qrySettlementInfo.BrokerID,m_pThostFtdcTraderSpiImpl->m_logininfo.BrokerID,sizeof(qrySettlementInfo.BrokerID));
        strncpy_s(qrySettlementInfo.InvestorID,m_pThostFtdcTraderSpiImpl->m_logininfo.UserID,sizeof(qrySettlementInfo.InvestorID));
        strncpy_s(qrySettlementInfo.ConfirmDate,m_pThostFtdcTraderSpiImpl->m_logininfo.TradingDay,sizeof(qrySettlementInfo.InvestorID));
        strncpy_s(qrySettlementInfo.ConfirmTime,Time.toStdString().c_str(),sizeof(qrySettlementInfo.InvestorID));

        m_pTradeUserApi->ReqSettlementInfoConfirm(&qrySettlementInfo,m_pThostFtdcTraderSpiImpl->GetRequestId());
    }else{
        //点击取消按钮
        ShowStatusTip(QStringLiteral("结算单未确认,不能进行交易!"));
    }
}
void MainWindow::SetStatusTip(QString str){

    m_pStatus->showMessage(str);
   // this->setStatusTip(str);
}
void MainWindow::ShowStatusTip(QString str){
    emit SigSetStatusTip(str);
}

void MainWindow::ShowStrategyTab(){
    m_Quottab->addTab(popmktcombineexch,QStringLiteral("日内交易策略"));
    m_Quottab->setCurrentIndex(2);//显示组合单Tab
}

void MainWindow::QuotTabDoubleClicked(int index){
    if(index != 0 && index != 1){
        m_Quottab->removeTab(index);
    }
}

bool MainWindow::InitTradeObject(QString strUserName,QString strPassword,QString strBrokerID,QString strServerName){

	m_szBrokerId = strBrokerID;
    m_szServerName = strServerName;

	QDir dir;
	QString currentPath=dir.currentPath();
	QString sParentDir = currentPath;
	QString sTradeDir;

	//创建TradeCon文件的目录
	sParentDir.append("/").append(strUserName);
	sTradeDir = sParentDir;
	sTradeDir.append("/TradeCon");

	if (!dir.exists(sParentDir)){
		if (!dir.mkdir(sParentDir)){
			QMessageBox::critical(NULL, QString("ERROR"), QString("创建账户目录失败"));
			return false;
		}
	}

	if (!dir.exists(sTradeDir)){
		if (!dir.mkdir(sTradeDir)){
			QMessageBox::critical(NULL, QString("ERROR"), QString("Fail To Create TradeConDir"));
			return false;
		}
	}
	sTradeDir = sTradeDir + "/";

	//初始化交易服务器
	m_pTradeUserApi = CThostFtdcTraderApi::CreateFtdcTraderApi(sTradeDir.toStdString().c_str());
	m_pThostFtdcTraderSpiImpl = new CThostFtdcTraderSpiImpl();
	m_pThostFtdcTraderSpiImpl->SetUserApi(m_pTradeUserApi);
	m_pThostFtdcTraderSpiImpl->SetUserAndPassword(m_szBrokerId,strUserName,strPassword);
	m_pThostFtdcTraderSpiImpl->SetMainDlg(this);
	m_pThostFtdcTraderSpiImpl->SetLoginDlg(g_pLoginDlg);
	m_pTradeUserApi->RegisterSpi((CThostFtdcTraderSpi*)m_pThostFtdcTraderSpiImpl);

	m_pTradeUserApi->SubscribePublicTopic(THOST_TERT_RESTART);
	m_pTradeUserApi->SubscribePrivateTopic(THOST_TERT_QUICK);

    QString qstrTradeFront("tcp://140.206.103.249:41205");
    if(m_ServerInfo.ServerName == m_szServerName){
        qstrTradeFront = "tcp://" + m_ServerInfo.ServerTradeAddr;
    }

    char*  pszTradeFront;
    QByteArray bTrade = qstrTradeFront.toLatin1();
    pszTradeFront=bTrade.data();

    //注册交易前置
    m_pTradeUserApi->RegisterFront(pszTradeFront);
    m_pTradeUserApi->Init();
	return true;
}

bool MainWindow::InitMdObject(QString strUserName,QString strPassword,QString strBrokerID){

	m_szBrokerId = strBrokerID;

	QDir dir;
	QString currentPath=dir.currentPath();
	QString sParentDir = currentPath;
	QString sMdDir;

	//创建MdCon文件的目录
	sParentDir.append("/").append(strUserName);
	sMdDir = sParentDir;
	sMdDir.append("/MdCon");

	if (!dir.exists(sParentDir))
	{
		if (!dir.mkdir(sParentDir))
		{
			QMessageBox::critical(NULL, QString("ERROR"), QString("创建账户目录失败"));
			return false;
		}
	}

	if (!dir.exists(sMdDir))
	{
		if (!dir.mkdir(sMdDir))
		{
			QMessageBox::critical(NULL, QString("ERROR"), QString("Fail To Create MdConDir"));
			return false;
		}
	}
	sMdDir = sMdDir + "/";

	//初始化行情服务器
	m_pmdUserApi = CThostFtdcMdApi::CreateFtdcMdApi(sMdDir.toStdString().c_str());
	m_pThostFtdcMdSpiImpl = new CThostFtdcMdSpiImpl();
	m_pThostFtdcMdSpiImpl->SetUserApi(m_pmdUserApi);
	m_pThostFtdcMdSpiImpl->SetUserAndPassword(m_szBrokerId,strUserName,strPassword);
	m_pThostFtdcMdSpiImpl->SetMainDlg(this);
	m_pmdUserApi->RegisterSpi((CThostFtdcMdSpi *)m_pThostFtdcMdSpiImpl);

    QString qstrMdFront("tcp://140.206.103.249:41213");
    if(m_ServerInfo.ServerName == m_szServerName){
        qstrMdFront = "tcp://" + m_ServerInfo.ServerMarketAddr;
    }

    char* pszMdFront;
    QByteArray bMd = qstrMdFront.toLatin1();
    pszMdFront=bMd.data();
    //注册行情前置
    m_pmdUserApi->RegisterFront(pszMdFront);
    m_pmdUserApi->Init();

	return true;
}

///组合单请求
//void MainWindow::AddNewCombineOrder(COMBINORDERINFO typeOrder){
    //m_pFundLib->NewCombineOrder(typeOrder);
    //m_tabWidget->setCurrentIndex(3);//组合单Tab显示
//}

///均价单请求
//void MainWindow::AddNewAverageOrder(AVERAGEORDERINFO averageOrder){
    //m_pFundLib->NewAverageOrder(averageOrder);
//}

///选择自选行情
void MainWindow::SelectSelfContract(const QModelIndex & oIndex){
    m_ControlDlg->hide();
    m_ControlDlg = m_SingleControlDlg;
    m_ControlDlg->show();

    m_SingleControlDlg->SelectContract(oIndex);
    mainaverageentrustwidget->SelectContract(oIndex);
}
///选择自定义组合行情
void MainWindow::SelectCombContract(const QModelIndex & oIndex){
    m_ControlDlg->hide();
    m_ControlDlg = m_CombineControlDlg;
    m_ControlDlg->show();

    m_CombineControlDlg->SelectCombContract(oIndex);
}

///行情服务器登录
void MainWindow::OnMdLogin(int iRetID, QString errInfo){
    if(iRetID == 0) {
        qDebug("Md Login Success");
        //订阅行情
        SubscribeMarketData();
    } else {
        qDebug("Md Login Failure");
    }
}
///交易服务器登录
void MainWindow::OnTdLogin(int iRetID, QString errInfo){
	if(iRetID == 0) {
		qDebug("Trader Login Success");
		//主界面显示资金账号
		m_SingleControlDlg->SetAccountID(m_pThostFtdcTraderSpiImpl->m_accountid);
		//资金Tab显示资金帐号
		mainbalancewidget->m_accountCombox->addItem(m_pThostFtdcTraderSpiImpl->m_accountid);
		//持仓Tab显示资金帐号
		mainholdwidget->m_accountCombox->addItem(m_pThostFtdcTraderSpiImpl->m_accountid);
		//查委托Tab显示资金账号
		mainentrustqueryhiswidget->m_accountCombox->addItem(m_pThostFtdcTraderSpiImpl->m_accountid);
		//查成交Tab显示资金账号
		mainbusinessqueryhiswidget->m_accountCombox->addItem(m_pThostFtdcTraderSpiImpl->m_accountid);
		//均价下单Tab显示资金帐号
		mainaverageentrustwidget->m_accountCombox->addItem(m_pThostFtdcTraderSpiImpl->m_accountid);
		//自定义组合单显示资金账号
		m_CombineControlDlg->SetAccountName(m_pThostFtdcTraderSpiImpl->m_accountid);

		//请求查询资金账户
		//ReqQryTradingAccount(this->m_pThostFtdcTraderSpiImpl->m_accountid);
		//请求查询投资者持仓
		//ReqQryInvestorPosition(this->m_pThostFtdcTraderSpiImpl->m_accountid);

		///请求查询所有合约
		CThostFtdcQryInstrumentField req;
		memset(&req, 0, sizeof(req));
		strcpy_s(req.InstrumentID, "");//为空表示查询所有合约
		m_pTradeUserApi->ReqQryInstrument(&req,m_pThostFtdcTraderSpiImpl->GetRequestId());

	} else {
		qDebug("Trader Login Failure");
	}

}
///读取Config.ini文件
void MainWindow::ReadConfigFile(){
    QString IniFilePath="Config.ini";
    QSettings* pConfigSettings = new QSettings(IniFilePath,QSettings::IniFormat);
    //从配置文件Config.ini读取自选合约信息
    m_iContractCount = pConfigSettings->value("ContractList/ContractCount","0").toInt();
    for(int iLoop = 0; iLoop < m_iContractCount; iLoop++){
        QString keyID = "ContractList/ContractID" + QString::number(iLoop,10);
        QString keyName = "ContractList/ContractName" + QString::number(iLoop,10);

        QString valueID =pConfigSettings->value(keyID,"").toString();
        QString valueName =pConfigSettings->value(keyName,"").toString();
        if(valueID != ""){
            CThostFtdcInstrumentField oInstrument;
            strncpy_s(oInstrument.InstrumentID,sizeof(TThostFtdcInstrumentIDType),valueID.toStdString().c_str(),sizeof(TThostFtdcInstrumentIDType));
            strncpy_s(oInstrument.InstrumentName,sizeof(TThostFtdcInstrumentNameType),valueName.toStdString().c_str(),sizeof(TThostFtdcInstrumentNameType));
            m_ContractVector.push_back(oInstrument);
        }
    }
    //读取自定义组合合约信息
    int iCombineSelfCount = pConfigSettings->value("CombineSelfList/CombineSelfCount","0").toInt();
    for(int iLoop = 0; iLoop < iCombineSelfCount; iLoop++){
        QString key = "CombineSelfList/CombineSelf" + QString::number(iLoop,10);
        QString value =pConfigSettings->value(key,"").toString();
        if(value != ""){
            QStringList tmplist = value.split("|");
            MarketComExchInstrument oMarketComExchInstrument;
            oMarketComExchInstrument.m_strLeg1 = tmplist.at(0);
            oMarketComExchInstrument.m_strLeg2 = tmplist.at(1);
            m_CombineSelfVector.push_back(oMarketComExchInstrument);
        }
    }
    //读取交易所组合合约信息
    int iCombineExchangeCount = pConfigSettings->value("CombineExchangeList/CombineExchangeCount","0").toInt();
    for(int iLoop = 0; iLoop < iCombineExchangeCount; iLoop++){
        QString key = "CombineExchangeList/CombineExchange" + QString::number(iLoop,10);
        QString value =pConfigSettings->value(key,"").toString();
        if(value != ""){
            m_CombineExchVector.push_back(value);
        }
    }
	//读取默认下单量信息
	int iDefaultOrderCnt = pConfigSettings->value("DafaultOrderCnt/ContractCnt","0").toInt();
	for (int iLoop = 0; iLoop < iDefaultOrderCnt; iLoop++){
		QString Namekey = "DafaultOrderCnt/ContractName" + QString::number(iLoop,10);
		QString Cntkey  = "DafaultOrderCnt/ContractCnt" + QString::number(iLoop,10);
		QString Name    = pConfigSettings->value(Namekey,"").toString();
		int     Cnt     = pConfigSettings->value(Cntkey,"").toInt();

		m_DefaultOrderCnt.insert(Name,Cnt);
	}

    delete pConfigSettings;
}
///投资者结算结果确认响应
void MainWindow::OnRspSettlementInfoConfirm(QString ConfirmDateTime){
	ShowStatusTip(QStringLiteral("投资者结算结果确认成功!确认时间:")+ConfirmDateTime);
}
///请求查询投资者结算结果响应
void MainWindow::OnRspQrySettlementInfo(CThostFtdcSettlementInfoField *pSettlementInfo, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast){
	
    m_SettlementInfoDialog->OutputContent(QString::fromLocal8Bit(pSettlementInfo->Content));
	if (bIsLast == true)
	{
		emit SigShowSettlementInfoDialog();
	}	
}
/**
 * 写入Config.ini文件
 * @brief MainWindow::WriteConfigFile
 * @param iGroupIndex 更新Config文件的内容
 */
void MainWindow::WriteConfigFile(int iGroupIndex){

    QString IniFilePath="Config.ini";
    QSettings* pConfigSettings = new QSettings(IniFilePath,QSettings::IniFormat);
    switch(iGroupIndex){
    case 1://自选合约行情
        pConfigSettings->setValue("ContractList/ContractCount",m_ContractVector.size());
        for(int iLoop = 0; iLoop < m_ContractVector.size(); iLoop++){
            QString keyID = "ContractList/ContractID" + QString::number(iLoop,10);
            QString keyName = "ContractList/ContractName" + QString::number(iLoop,10);
            pConfigSettings->setValue(keyID,m_ContractVector[iLoop].InstrumentID);
            pConfigSettings->setValue(keyName,m_ContractVector[iLoop].InstrumentName);
        }
        break;
    case 2://自定义组合行情
        pConfigSettings->setValue("CombineSelfList/CombineSelfCount",m_CombineSelfVector.size());
        for(int iLoop = 0; iLoop < m_CombineSelfVector.size(); iLoop++){
            QString key = "CombineSelfList/CombineSelf" + QString::number(iLoop,10);
            QString value = m_CombineSelfVector[iLoop].m_strLeg1 + "|" + m_CombineSelfVector[iLoop].m_strLeg2;
            pConfigSettings->setValue(key,value);
        }
        break;
    case 3://交易所组合行情
        break;
    default:
        break;
    }
    delete pConfigSettings;
}

void MainWindow::destroyWin(){
    mainwidget->close();
    delete m_MainPopDialog;
    delete m_SelfMarketDialog;
    delete m_PopMktCombineExchDialog;
    delete m_CombineExchDialog;
    delete m_DefaultOrderDialog;
    delete m_QuickOrderDialog;
    delete m_CombineOrderDialog;
    dialog2 = NULL;
}

/**
 * 更新选定的自定义行情信息
 * @brief MainWindow::UpdateMarketdata
 */
void MainWindow::UpdateMarketdata(){
    //退订之前订阅的合约信息
    if (m_iContractCount > 0)
    {
        m_pmdUserApi->UnSubscribeMarketData(m_Instrument,m_iContractCount);

        for (int i = 0; i < m_iContractCount ; i++)
        {
            delete m_Instrument[i];
        }
        delete m_Instrument;
        m_iContractCount = 0;
    }
    //清空行情列表中的内容
    marketselfwidget->m_tableView->clear();
    //订阅行情
    SubscribeMarketData();
    //更新Config文件
    WriteConfigFile(1);
}

/**
 * 更新选定的自定义组合行情信息
 * @brief MainWindow::UpdateCombineMarketdata
 */
void MainWindow::UpdateCombineMarketdata(){
    ///退订之前订阅的合约信息
    if (m_iContractCount > 0)
    {
        m_pmdUserApi->UnSubscribeMarketData(m_Instrument,m_iContractCount);

        for (int i = 0; i < m_iContractCount ; i++)
        {
            delete m_Instrument[i];
        }
        delete m_Instrument;
        m_iContractCount = 0;
    }
    //清空行情列表中的内容
    marketcomexch->m_tableView->clear();
    //订阅行情
    SubscribeMarketData();
    //更新Config文件
    WriteConfigFile(2);
}
void MainWindow::CreateMainPopDlg(int iIndex){
    ///初始化各设置对话框
    m_SelfMarketDialog = new SelfMarketDialog(this);
    m_PopMktCombineExchDialog = new PopMktCombineExchDialog(this);
    m_CombineExchDialog = new CombineExchDialog(this);
    m_DefaultOrderDialog = new DefaultOrderDialog(this);
    m_QuickOrderDialog = new QuickOrderDialog();
    m_CombineOrderDialog = new CombineOrderDialog();
    m_SelfMarketDialog->setFixedSize(600,400);
    m_PopMktCombineExchDialog->setFixedSize(600,400);
    m_CombineExchDialog->setFixedSize(600,400);
    m_DefaultOrderDialog->setFixedSize(600,400);
    m_QuickOrderDialog->setFixedSize(600,400);
    m_CombineOrderDialog->setFixedSize(600,400);

    m_MainPopDialog = new MainPopDialog;  // 用于显示界面的父窗体QDialog(QWidget的子类）
    m_MainPopDialog->setFixedSize(150,350);
    m_MainPopDialog->setWindowFlags(Qt::WindowStaysOnTopHint);
    switch(iIndex){
    case 0:
        dialog2 = m_SelfMarketDialog;break;
    case 1:
        dialog2 = m_PopMktCombineExchDialog;break;
    case 2:
        dialog2 = m_CombineExchDialog;break;
    case 3:
        dialog2 = m_DefaultOrderDialog;break;
    case 4:
        dialog2 = m_QuickOrderDialog;break;
    case 5:
        dialog2 = m_CombineOrderDialog;break;
    default:
        break;
    }

    mainwidget = new QWidget;
    mainwidget->setWindowTitle(QStringLiteral("选项设置"));
    mainlayout = new QGridLayout;
    mainlayout->addWidget(m_MainPopDialog,0,0,1,1);
    mainlayout->addWidget(m_SelfMarketDialog,0,1,1,2);
    mainlayout->addWidget(m_PopMktCombineExchDialog,0,1,1,2);
    mainlayout->addWidget(m_CombineExchDialog,0,1,1,2);
    mainlayout->addWidget(m_DefaultOrderDialog,0,1,1,2);
    mainlayout->addWidget(m_QuickOrderDialog,0,1,1,2);
    mainlayout->addWidget(m_CombineOrderDialog,0,1,1,2);

    m_SelfMarketDialog->hide();
    m_PopMktCombineExchDialog->hide();
    m_CombineExchDialog->hide();
    m_DefaultOrderDialog->hide();
    m_QuickOrderDialog->hide();
    m_CombineOrderDialog->hide();

    buttonlayout = new QHBoxLayout;
    confirmbutton = new QPushButton(QStringLiteral("确定"));
    cancelbutton = new QPushButton(QStringLiteral("取消"));
    confirmbutton->setFixedWidth(80);
    cancelbutton->setFixedWidth(80);

    buttonlayout->addWidget(confirmbutton);
    buttonlayout->addWidget(cancelbutton);

    mainlayout->addLayout(buttonlayout,1,2,1,1);

    mainwidget->setLayout(mainlayout);
    mainwidget->setWindowFlags(mainwidget->windowFlags()& ~Qt::WindowMaximizeButtonHint& ~Qt::WindowMinimizeButtonHint);
    mainwidget->show();
    dialog2->show();

	connect(((SelfMarketDialog*)m_SelfMarketDialog), SIGNAL(SubscribeMarketData()), this, SLOT(UpdateMarketdata()));
	connect(((PopMktCombineExchDialog*)m_PopMktCombineExchDialog), SIGNAL(UpdateCombineMarketdata()), this, SLOT(UpdateCombineMarketdata()));

    connect(((MainPopDialog*)m_MainPopDialog)->ui->treeWidget, SIGNAL(itemPressed(QTreeWidgetItem*,int)), this, SLOT(slotItemPressed(QTreeWidgetItem*,int)));
    //OK按钮响应事件
    connect(confirmbutton,SIGNAL(clicked()),dialog2,SLOT(OKButtonClicked()));
    connect(dialog2,SIGNAL(destroyWin()),this,SLOT(destroyWin()));
    //Cancel按钮响应事件
    connect(cancelbutton,SIGNAL(clicked()),this,SLOT(destroyWin()));
}
///自选行情设置
void MainWindow::selfdialogshow()
{
    CreateMainPopDlg(0);
}
///自定义组合行情
void MainWindow::marketcomexchdialogshow()
{
     CreateMainPopDlg(1);
}
///交易所组合行情
void MainWindow::combineexchdialogshow()
{
     CreateMainPopDlg(2);
}
///默认下单量设置
void MainWindow::defaultorderdialogshow()
{
     CreateMainPopDlg(3);
}
///快速下单设置
void MainWindow::quickorderdialogshow()
{
     CreateMainPopDlg(4);
}
///组合单参数设置
void MainWindow::combineorderdialogshow()
{
     CreateMainPopDlg(5);
}

void MainWindow::slotItemPressed(QTreeWidgetItem *item, int column)
{
    dialog2->hide();
    disconnect(confirmbutton,SIGNAL(clicked()),dialog2,SLOT(OKButtonClicked()));
    disconnect(dialog2,SIGNAL(destroyWin()),this,SLOT(destroyWin()));

    QString text = item->text(column);
    if(text==QStringLiteral("自选行情设置")){
        dialog2 = m_SelfMarketDialog;
    }else if(text==QStringLiteral("自定义组合设置")){
        dialog2 = m_PopMktCombineExchDialog;
    }else if(text==QStringLiteral("交易所组合行情")){
        dialog2 = m_CombineExchDialog;
    }else if(text==QStringLiteral("默认下单量设置")){
        dialog2 = m_DefaultOrderDialog;
    }else if(text==QStringLiteral("快速下单设置")){
        dialog2 = m_QuickOrderDialog;
    }else if(text==QStringLiteral("组合单参数设置")){
        dialog2 = m_CombineOrderDialog;
    }
    //OK按钮响应事件切换
    connect(confirmbutton,SIGNAL(clicked()),dialog2,SLOT(OKButtonClicked()));
    connect(dialog2,SIGNAL(destroyWin()),this,SLOT(destroyWin()));
    dialog2->show();
}
//退出服务器
void MainWindow::exit()
{
    RegisterSpi();
    this->close();
}

void MainWindow::RegisterSpi(){
    if(this->m_pmdUserApi){
        this->m_pmdUserApi->RegisterSpi(NULL);
        this->m_pmdUserApi->Release();
        this->m_pmdUserApi=NULL;
    }
    if(this->m_pThostFtdcMdSpiImpl){
        delete this->m_pThostFtdcMdSpiImpl;
        this->m_pThostFtdcMdSpiImpl=NULL;
    }
    qDebug("Market Server Logout Success");

    if(this->m_pTradeUserApi){
        this->m_pTradeUserApi->RegisterSpi(NULL);
        this->m_pTradeUserApi->Release();
        this->m_pTradeUserApi = NULL;
    }
    if(this->m_pThostFtdcTraderSpiImpl){
        delete this->m_pThostFtdcTraderSpiImpl;
        this->m_pThostFtdcTraderSpiImpl = NULL;
    }
    qDebug("Trader Server Logout Success");
}

//订阅行情
void MainWindow::SubscribeMarketData(){

    QMap<QString,int> tmpContracts;
    //自选合约行情
    for(int i = 0 ; i<m_ContractVector.size(); i++){
        CThostFtdcInstrumentField oInstrument = m_ContractVector[i];
        tmpContracts.insert(QString(oInstrument.InstrumentID),i);
    }
    //自定义组合合约
    for(int j = 0 ; j<m_CombineSelfVector.size(); j++){
        MarketComExchInstrument oMarketComExchInstrument = m_CombineSelfVector[j];
        tmpContracts.insert(oMarketComExchInstrument.m_strLeg1,j);
        tmpContracts.insert(oMarketComExchInstrument.m_strLeg2,j);
    }
    //交易所组合合约
    for(int k = 0; k < m_CombineExchVector.size(); k++){
        tmpContracts.insert(m_CombineExchVector[k],k);
    }

    m_iContractCount = tmpContracts.size();
	if(m_iContractCount > 0 ){
		m_Instrument=new char*[m_iContractCount];
        int iIndex = 0;
        for (QMap<QString,int>::Iterator iter = tmpContracts.begin(); iter != tmpContracts.end(); ++iter ) {
            QString sInstrument = iter.key();

            char* Instrtmp = new char [sizeof(TThostFtdcInstrumentIDType)];
            strncpy_s(Instrtmp,sizeof(TThostFtdcInstrumentIDType),sInstrument.toStdString().c_str(),sizeof(TThostFtdcInstrumentIDType));
            m_Instrument[iIndex]=Instrtmp;
            iIndex++;
        }
		if (m_pmdUserApi != NULL)
		{
			m_pmdUserApi->SubscribeMarketData(m_Instrument,m_iContractCount);
		}		
	}    
}

///删除预埋单
void MainWindow::RemoveParkedOrder(CThostFtdcRemoveParkedOrderField* pOrder){
	this->m_pTradeUserApi->ReqRemoveParkedOrder(pOrder,this->m_pThostFtdcTraderSpiImpl->GetRequestId());
}
///查询资金账户
void MainWindow::ReqQryTradingAccount(QString strAccountID){
    CThostFtdcQryTradingAccountField oQryTradingAccount;
    memset(&oQryTradingAccount,0,sizeof(CThostFtdcQryTradingAccountField));
    strcpy(oQryTradingAccount.BrokerID   , m_pThostFtdcTraderSpiImpl->m_logininfo.BrokerID);///经纪公司代码
    strcpy(oQryTradingAccount.InvestorID , strAccountID.toStdString().c_str());///投资者代码
    strcpy(oQryTradingAccount.CurrencyID , "CNY");///币种代码

    m_pTradeUserApi->ReqQryTradingAccount(&oQryTradingAccount,m_pThostFtdcTraderSpiImpl->GetRequestId());
}
///请求查询投资者持仓
void MainWindow::ReqQryInvestorPosition(QString strAccountID){
    //清除保存的用户持仓信息
    m_positionlist.clear();

    CThostFtdcQryInvestorPositionField posinfo;
    memset(&posinfo,0,sizeof(CThostFtdcQryInvestorPositionField));
    strncpy_s(posinfo.BrokerID,m_pThostFtdcTraderSpiImpl->m_logininfo.BrokerID,sizeof(TThostFtdcBrokerIDType));///经纪公司代码
    strncpy_s(posinfo.InvestorID,strAccountID.toStdString().c_str(),sizeof(TThostFtdcInvestorIDType));///投资者代码

    m_pTradeUserApi->ReqQryInvestorPosition(&posinfo,this->m_pThostFtdcTraderSpiImpl->GetRequestId());
}
///请求查询报单
void MainWindow::QueryOrder(QStringList strAttrs){
    CThostFtdcQryOrderField queryinfo;
    memset(&queryinfo,0,sizeof(CThostFtdcQryOrderField));

    strncpy_s(queryinfo.BrokerID,m_pThostFtdcTraderSpiImpl->m_logininfo.BrokerID,sizeof(TThostFtdcBrokerIDType));
	if (strAttrs.size() == 1)
	{
		strncpy_s(queryinfo.InvestorID,strAttrs.at(0).toStdString().c_str(),sizeof(TThostFtdcInvestorIDType));
	}else if (strAttrs.size() == 3)
	{
		strncpy_s(queryinfo.InvestorID,strAttrs.at(0).toStdString().c_str(),sizeof(TThostFtdcInvestorIDType));
		//strncpy_s(queryinfo.InsertTimeStart,strAttrs.at(0).toStdString().c_str(),sizeof(TThostFtdcInvestorIDType));
		///开始时间
		//TThostFtdcTimeType	InsertTimeStart;
		///结束时间
		//TThostFtdcTimeType	InsertTimeEnd;
	}
    m_pTradeUserApi->ReqQryOrder(&queryinfo,this->m_pThostFtdcTraderSpiImpl->GetRequestId());
}
///请求查询成交
void MainWindow::ReqQryTrade(QString strAccountID){
    CThostFtdcQryTradeField tradoinfo;
    memset(&tradoinfo,0,sizeof(CThostFtdcQryTradeField));

    strncpy_s(tradoinfo.BrokerID,m_pThostFtdcTraderSpiImpl->m_logininfo.BrokerID,sizeof(TThostFtdcBrokerIDType));
    strncpy_s(tradoinfo.InvestorID,strAccountID.toStdString().c_str(),sizeof(TThostFtdcInvestorIDType));
    m_pTradeUserApi->ReqQryTrade(&tradoinfo,this->m_pThostFtdcTraderSpiImpl->GetRequestId());
}
///请求查询报单响应
void MainWindow::OnRspQryOrder(CThostFtdcOrderField *pOrder) 
{
	mainentrustqueryhiswidget->ShowOrderDetails(pOrder);
}
///请求查询成交响应
void MainWindow::OnRspQryTrade(CThostFtdcTradeField *pTrade){
	mainbusinessqueryhiswidget->ShowTradeDetails(pTrade);
}
///预埋单录入请求响应
void MainWindow::OnRspParkedOrderInsert(CThostFtdcParkedOrderField *pParkedOrder){
	mainpreentrustwidget->ShowParkedOrders(pParkedOrder);
    m_tabWidget->setCurrentIndex(1);//预埋单Tab显示
}
///均价单显示
void MainWindow::ShowAverageOrder(int icnt, void* pData){
	mainaverageentrustwidget->ShowAverageOrder(icnt,pData);
}

///组合单显示   从通讯服务器返回结果之后，对组合单进行存储
void MainWindow::ShowCombineOrder(int icnt, void* pData){
	maincombineentrustwidget->ShowCombineOrder(icnt,pData);

    /*COMBINORDERINFO* pOrderInfo = (COMBINORDERINFO*)pData;

	for(int i = 0; i < icnt; i++)
	{//--存储到队列中--
		QString strKey  = QString::number(pOrderInfo[i].OrderID);
		STCombineInfo* stCombine = new STCombineInfo;
		stCombine->dDownPrice1=0;
		stCombine->dDownPrice2=0;
		stCombine->dUpPrice1=0;
		stCombine->dUpPrice2=0;
		stCombine->var0_CombineNumber= QString::number(pOrderInfo[i].OrderID); 
		stCombine->var10_sStatus= ComFunc::GetCofcoStatusName(pOrderInfo[i].EnableStatus); 
		stCombine->SendHand1= 0;
		stCombine->SendHand2= 0;
		stCombine->BusHand1= 0;
		stCombine->BusHand2= 0;
		stCombine->dBussPrice =0;
		stCombine->var15_sEntrustTime= QString::number(pOrderInfo[i].EntrustTime); 
		stCombine->var16_sEnableStatus= "开启";
		stCombine->var1_szAccount= QString(pOrderInfo[i].AccountID); 
		stCombine->var2_sLeg1= QString(pOrderInfo[i].FirstContractID); 
		stCombine->var3_sLeg2= QString(pOrderInfo[i].SecondContractID);
		stCombine->var4_sOrderType= ComFunc::GetCofcoOrderType(pOrderInfo[i].Type +1);
		stCombine->var5_sBsName= ComFunc::GetBSName( pOrderInfo[i].BS);
		stCombine->var6_sOcName= ComFunc::GetOCName( pOrderInfo[i].OC);
		stCombine->TotalHand=  pOrderInfo[i].EntrustAmount;
		stCombine->var8_Price= pOrderInfo[i].EntrustPrice;
		stCombine->var9_sHedge1= ComFunc::GetHedgeType(pOrderInfo[i].FirstBase -1);
		stCombine->var9_sHedge2= ComFunc::GetHedgeType(pOrderInfo[i].SecondBase -1);

		stCombine->bRspBusinessLeg1= TRUE;
		stCombine->bRspEntrustLeg1= TRUE;
		stCombine->bRspOrderLeg1=TRUE;
		stCombine->bRspBusinessLeg2= TRUE;
		stCombine->bRspEntrustLeg2= TRUE;
		stCombine->bRspOrderLeg2=TRUE;
		stCombine->iLastEntrustTime= 0;

		m_CombineOrderVector.push_back(stCombine);
    }*/
}
///组合单行情推送，并对组合单进行判断以进行下单
//                                                             现买量                   现买价          现卖量               现卖价
void MainWindow::SlotCombineOrder(QString Leg1,QString Leg2,int buy_high_amount,QString csBuyPrice,int sale_low_amount,QString csSellPrice){
	// 现买价  第一腿的申买价  减去 第二腿的申卖价
	// 现卖价  第一腿的申卖价  减去 第二腿的申买价
	for ( int i = 0; i < m_CombineOrderVector.size(); i++ ) {  
		STCombineInfo* stCombine = m_CombineOrderVector[i];

		//判断组合单中两腿合约代码
		if (stCombine->var2_sLeg1 == Leg1  && stCombine->var3_sLeg2 == Leg2 && csBuyPrice != "-" && csSellPrice != "-"){
			if (csBuyPrice.toDouble() >= stCombine->var8_Price){ //现买价 与 委托价差 进行比较//当现买价不小于委托价差时 进行下单操作
				if (stCombine->TotalHand > 0){ //判断手数
					//先对第一腿合约进行下单
					CThostFtdcInputOrderField OrderInfo;
					memset(&OrderInfo, 0, sizeof(CThostFtdcInputOrderField));
					///合约代码
					strncpy(OrderInfo.InstrumentID, Leg1.toStdString().c_str(), sizeof(TThostFtdcInstrumentIDType));
					///买卖方向
					OrderInfo.Direction = THOST_FTDC_D_Buy;///买入
					//市价
					///报单价格条件类型：任意价
					OrderInfo.OrderPriceType = THOST_FTDC_OPT_AnyPrice;
					///价格
					OrderInfo.LimitPrice = 0;
					///有效期类型：立即完成，否则撤销
					OrderInfo.TimeCondition =   THOST_FTDC_TC_IOC;
					//开仓
					OrderInfo.CombOffsetFlag[0]='0';
					///组合投机套保标志 //0投机；1套保
					OrderInfo.CombHedgeFlag[0]='1'	;
					///数量
					OrderInfo.VolumeTotalOriginal = 1;
					///成交量类型 任意数量
					OrderInfo.VolumeCondition = THOST_FTDC_VC_AV;
					///触发条件:立即
					OrderInfo.ContingentCondition = THOST_FTDC_CC_Immediately;

					///最小成交量 1
					OrderInfo.MinVolume = 1;
					///强平原因 非强平
					OrderInfo.ForceCloseReason = THOST_FTDC_FCC_NotForceClose;
					///自动挂起标志 否
					OrderInfo.IsAutoSuspend = 0;
					///用户强平标志 否
					OrderInfo.UserForceClose = 0;
					OnCombineOrderInsert(&OrderInfo,stCombine->var0_CombineNumber);//进行报单

					//////////////////////////////////////////////////////////////////////////
					///再对第二腿合约进行下单
					//////////////////////////////////////////////////////////////////////////
					///合约代码
					strncpy(OrderInfo.InstrumentID, Leg2.toStdString().c_str(), sizeof(TThostFtdcInstrumentIDType));
					///买卖方向
					OrderInfo.Direction = THOST_FTDC_D_Sell;///卖出
					//市价
					///报单价格条件类型：任意价
					OrderInfo.OrderPriceType = THOST_FTDC_OPT_AnyPrice;
					///价格
					OrderInfo.LimitPrice = 0;
					///有效期类型：立即完成，否则撤销
					OrderInfo.TimeCondition =   THOST_FTDC_TC_IOC;
					//开仓
					OrderInfo.CombOffsetFlag[0]='0';
					///组合投机套保标志 //0投机；1套保
					OrderInfo.CombHedgeFlag[0]='1'	;
					///数量
					OrderInfo.VolumeTotalOriginal = 1;
					///成交量类型 任意数量
					OrderInfo.VolumeCondition = THOST_FTDC_VC_AV;
					///触发条件:立即
					OrderInfo.ContingentCondition = THOST_FTDC_CC_Immediately;

					///最小成交量 1
					OrderInfo.MinVolume = 1;
					///强平原因 非强平
					OrderInfo.ForceCloseReason = THOST_FTDC_FCC_NotForceClose;
					///自动挂起标志 否
					OrderInfo.IsAutoSuspend = 0;
					///用户强平标志 否
					OrderInfo.UserForceClose = 0;
					OnCombineOrderInsert(&OrderInfo,stCombine->var0_CombineNumber);//进行报单

					stCombine->TotalHand = stCombine->TotalHand  -1;
				}				
			}
		}
	}
}
///组合单报单请求
void MainWindow::OnCombineOrderInsert(CThostFtdcInputOrderField *pInputOrder,QString CombineNo){
	//报单引用
	TThostFtdcOrderRefType NewOrderRef;
	int iOrderRef;

	strncpy_s(NewOrderRef,sizeof(TThostFtdcOrderRefType),m_pThostFtdcTraderSpiImpl->m_logininfo.MaxOrderRef,sizeof(TThostFtdcOrderRefType));
	iOrderRef=atoi(NewOrderRef);
	iOrderRef++;
	itoa(iOrderRef,NewOrderRef,10);
	strncpy_s(m_pThostFtdcTraderSpiImpl->m_logininfo.MaxOrderRef,sizeof(TThostFtdcOrderRefType),NewOrderRef,sizeof(TThostFtdcOrderRefType));

	strncpy_s(pInputOrder->BrokerID,sizeof(TThostFtdcBrokerIDType),m_pThostFtdcTraderSpiImpl->m_logininfo.BrokerID,sizeof(TThostFtdcBrokerIDType));
	strncpy_s(pInputOrder->InvestorID,sizeof(TThostFtdcInvestorIDType),m_pThostFtdcTraderSpiImpl->m_logininfo.UserID,sizeof(TThostFtdcInvestorIDType));
	strncpy_s(pInputOrder->OrderRef,sizeof(TThostFtdcOrderRefType),m_pThostFtdcTraderSpiImpl->m_logininfo.MaxOrderRef,sizeof(TThostFtdcOrderRefType));
	strncpy_s(pInputOrder->UserID,sizeof(TThostFtdcUserIDType),m_pThostFtdcTraderSpiImpl->m_logininfo.UserID,sizeof(TThostFtdcUserIDType));

	this->m_pTradeUserApi->ReqOrderInsert(pInputOrder,this->m_pThostFtdcTraderSpiImpl->GetRequestId());
	m_CombineMap.insert(iOrderRef,CombineNo);//存储 报单号与组合单号的对应关系
}
///查询资金账户响应
void MainWindow::OnRspQryTradingAccount(CThostFtdcTradingAccountField *pTradingAccount, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast){
	if(NULL != pTradingAccount){
		mainbalancewidget->ShowTradingAccount(pTradingAccount);
	}
    if(bIsLast == true){
        ShowStatusTip(QStringLiteral("查询资金账户成功!"));
    }
}
///查询持仓响应
void MainWindow::OnRspQryInvestorPosition(CThostFtdcInvestorPositionField *pInvestorPosition, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast){

    if(NULL != pInvestorPosition){
        mainholdwidget->ShowInvestorPosition(pInvestorPosition);

        CThostFtdcInvestorPositionField myPosition;
        memcpy_s(&myPosition,sizeof(CThostFtdcInvestorPositionField),pInvestorPosition,sizeof(CThostFtdcInvestorPositionField));
        //保存用户的持仓信息
        m_positionlist.push_back(myPosition);
    }
    if(bIsLast == true){
        ShowStatusTip(QStringLiteral("查询持仓成功!"));
    }
}

void MainWindow::OnRspQryInstrument(CThostFtdcInstrumentField *pInstrument, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast){
	
	CThostFtdcInstrumentField InstruDetailInfo;
	QString sInstrumentID = pInstrument->InstrumentID;
	QString sExchangeID = pInstrument->ExchangeID;

	memcpy(&InstruDetailInfo,pInstrument,sizeof(InstruDetailInfo));

    if (sExchangeID == "CZCE"){//郑州
		m_CZCEInstrumentMap.insert(sInstrumentID,InstruDetailInfo);
    }else if(sExchangeID == "SHFE"){//上海
		m_SHFEInstrumentMap.insert(sInstrumentID,InstruDetailInfo);
    }else if(sExchangeID == "CFFEX"){//金融
        m_CFFEXInstrumentMap.insert(sInstrumentID,InstruDetailInfo);
    }else if(sExchangeID == "DCE"){//大连
		m_DCEInstrumentMap.insert(sInstrumentID,InstruDetailInfo);
	}else{
		qDebug("Other ExchangeID");
	}

	++m_lInstrumentCount;
    //显示合约信息至 查询合约 Tab中
    maincontractwidget->AddRow(pInstrument);

    if (bIsLast){
        ShowStatusTip(QStringLiteral("查询获取全部合约信息成功"));
        //显示合约信息至 查询合约 Tab中
        //maincontractwidget->AddRows(m_CZCEInstrumentMap);
        //maincontractwidget->AddRows(m_SHFEInstrumentMap);
        //maincontractwidget->AddRows(m_CFFEXInstrumentMap);
        //maincontractwidget->AddRows(m_DCEInstrumentMap);

        Sleep(1000);
        //请求查询结算信息确认
        CThostFtdcQrySettlementInfoConfirmField oQrySettlementInfoConfirm;
        strncpy_s(oQrySettlementInfoConfirm.BrokerID,this->m_pThostFtdcTraderSpiImpl->m_logininfo.BrokerID,sizeof(oQrySettlementInfoConfirm.BrokerID));///经纪公司代码
        strncpy_s(oQrySettlementInfoConfirm.InvestorID,this->m_pThostFtdcTraderSpiImpl->m_logininfo.UserID,sizeof(oQrySettlementInfoConfirm.InvestorID));///投资者代码

        this->m_pTradeUserApi->ReqQrySettlementInfoConfirm(&oQrySettlementInfoConfirm,this->m_pThostFtdcTraderSpiImpl->GetRequestId());
    }
}

char* MainWindow::GetExchangeID(char*	InstrumentID){
	//郑州交易所
    if(true == m_CZCEInstrumentMap.contains(QString(InstrumentID))){
        return "CZCE";
    }
	//上海交易所
    if(true == m_SHFEInstrumentMap.contains(QString(InstrumentID))){
        return "SHFE";
    }
	//中国金融期货交易所
    if(true == m_CFFEXInstrumentMap.contains(QString(InstrumentID))){
        return "CFFEX";
    }
	//大连交易所
    if(true == m_DCEInstrumentMap.contains(QString(InstrumentID))){
        return "DCE";
    }
}
///撤销委托
void MainWindow::DeleteOrder(QString strLocalOrderID){
	if (true == this->mainorderwidget->m_EntrustOrderMap.contains(strLocalOrderID)){
		CThostFtdcOrderField oOrder = this->mainorderwidget->m_EntrustOrderMap.find(strLocalOrderID).value();

		CThostFtdcInputOrderActionField req;
		memset(&req, 0, sizeof(req));
		strncpy_s(req.BrokerID,sizeof(TThostFtdcBrokerIDType),oOrder.BrokerID,sizeof(TThostFtdcBrokerIDType));
		strncpy_s(req.InvestorID,sizeof(TThostFtdcInvestorIDType),oOrder.UserID,sizeof(TThostFtdcInvestorIDType));
		strncpy_s(req.ExchangeID,sizeof(TThostFtdcExchangeIDType),oOrder.ExchangeID,sizeof(TThostFtdcExchangeIDType));
		strncpy_s(req.OrderSysID, sizeof(TThostFtdcOrderSysIDType),oOrder.OrderSysID,sizeof(TThostFtdcOrderSysIDType));
		req.ActionFlag = THOST_FTDC_AF_Delete;  //操作标志

		m_pTradeUserApi->ReqOrderAction(&req,this->m_pThostFtdcTraderSpiImpl->GetRequestId());
	}
}
///撤销全部委托
void MainWindow::DeleteAllOrders(){
    QMap<QString,CThostFtdcOrderField>::iterator iter;
    for(iter = this->mainorderwidget->m_EntrustOrderMap.begin(); iter != this->mainorderwidget->m_EntrustOrderMap.end(); ++iter){
        CThostFtdcOrderField oOrder = iter.value();
		if(oOrder.OrderStatus == THOST_FTDC_OST_PartTradedQueueing ||//部分成交还在队列中
			oOrder.OrderStatus == THOST_FTDC_OST_NoTradeQueueing){//未成交还在队列中
			CThostFtdcInputOrderActionField req;
			memset(&req, 0, sizeof(req));
			strncpy_s(req.BrokerID,sizeof(TThostFtdcBrokerIDType),oOrder.BrokerID,sizeof(TThostFtdcBrokerIDType));
			strncpy_s(req.InvestorID,sizeof(TThostFtdcInvestorIDType),oOrder.UserID,sizeof(TThostFtdcInvestorIDType));
			strncpy_s(req.ExchangeID,sizeof(TThostFtdcExchangeIDType),oOrder.ExchangeID,sizeof(TThostFtdcExchangeIDType));
			strncpy_s(req.OrderSysID, sizeof(TThostFtdcOrderSysIDType),oOrder.OrderSysID,sizeof(TThostFtdcOrderSysIDType));
			req.ActionFlag = THOST_FTDC_AF_Delete;  //操作标志

			m_pTradeUserApi->ReqOrderAction(&req,this->m_pThostFtdcTraderSpiImpl->GetRequestId());
		}
    }
}
///条件单请求
void MainWindow::OnConditonOrderInsert(CThostFtdcInputOrderField* pOrder,ConditionType* pCondition){
	//报单引用
	TThostFtdcOrderRefType NewOrderRef;
	int iOrderRef;

	strncpy_s(NewOrderRef,sizeof(TThostFtdcOrderRefType),m_pThostFtdcTraderSpiImpl->m_logininfo.MaxOrderRef,sizeof(TThostFtdcOrderRefType));
	iOrderRef=atoi(NewOrderRef);
	iOrderRef++;
	itoa(iOrderRef,NewOrderRef,10);
	strncpy_s(m_pThostFtdcTraderSpiImpl->m_logininfo.MaxOrderRef,sizeof(TThostFtdcOrderRefType),NewOrderRef,sizeof(TThostFtdcOrderRefType));

	strncpy_s(pOrder->OrderRef,sizeof(TThostFtdcOrderRefType),m_pThostFtdcTraderSpiImpl->m_logininfo.MaxOrderRef,sizeof(TThostFtdcOrderRefType));
	strncpy_s(pOrder->BrokerID,sizeof(TThostFtdcBrokerIDType),m_pThostFtdcTraderSpiImpl->m_logininfo.BrokerID,sizeof(TThostFtdcBrokerIDType));
	strncpy_s(pOrder->InvestorID,sizeof(TThostFtdcInvestorIDType),m_pThostFtdcTraderSpiImpl->m_logininfo.UserID,sizeof(TThostFtdcInvestorIDType));
	strncpy_s(pOrder->UserID,sizeof(TThostFtdcUserIDType),m_pThostFtdcTraderSpiImpl->m_logininfo.UserID,sizeof(TThostFtdcUserIDType));

	this->m_pTradeUserApi->ReqOrderInsert(pOrder,this->m_pThostFtdcTraderSpiImpl->GetRequestId());
}

///预埋单请求
void MainWindow::OnParkedOrderInsert(CThostFtdcParkedOrderField *pParkedOrder){
    //报单引用
    TThostFtdcOrderRefType NewOrderRef;
    int iOrderRef;

    strncpy_s(NewOrderRef,sizeof(TThostFtdcOrderRefType),m_pThostFtdcTraderSpiImpl->m_logininfo.MaxOrderRef,sizeof(TThostFtdcOrderRefType));
    iOrderRef=atoi(NewOrderRef);
    iOrderRef++;
    itoa(iOrderRef,NewOrderRef,10);
    strncpy_s(m_pThostFtdcTraderSpiImpl->m_logininfo.MaxOrderRef,sizeof(TThostFtdcOrderRefType),NewOrderRef,sizeof(TThostFtdcOrderRefType));

    strncpy_s(pParkedOrder->BrokerID,sizeof(TThostFtdcBrokerIDType),m_pThostFtdcTraderSpiImpl->m_logininfo.BrokerID,sizeof(TThostFtdcBrokerIDType));
    strncpy_s(pParkedOrder->InvestorID,sizeof(TThostFtdcInvestorIDType),m_pThostFtdcTraderSpiImpl->m_logininfo.UserID,sizeof(TThostFtdcInvestorIDType));
    strncpy_s(pParkedOrder->OrderRef,sizeof(TThostFtdcOrderRefType),m_pThostFtdcTraderSpiImpl->m_logininfo.MaxOrderRef,sizeof(TThostFtdcOrderRefType));
    strncpy_s(pParkedOrder->UserID,sizeof(TThostFtdcUserIDType),m_pThostFtdcTraderSpiImpl->m_logininfo.UserID,sizeof(TThostFtdcUserIDType));

    this->m_pTradeUserApi->ReqParkedOrderInsert(pParkedOrder,this->m_pThostFtdcTraderSpiImpl->GetRequestId());
}
///均价单报单请求
void MainWindow::OnOrderInsert(CThostFtdcInputOrderField* pInputOrder,QString AverageNo){
	//报单引用
	TThostFtdcOrderRefType NewOrderRef;
	int iOrderRef;

	strncpy_s(NewOrderRef,sizeof(TThostFtdcOrderRefType),m_pThostFtdcTraderSpiImpl->m_logininfo.MaxOrderRef,sizeof(TThostFtdcOrderRefType));
	iOrderRef=atoi(NewOrderRef);
	iOrderRef++;
	itoa(iOrderRef,NewOrderRef,10);
	strncpy_s(m_pThostFtdcTraderSpiImpl->m_logininfo.MaxOrderRef,sizeof(TThostFtdcOrderRefType),NewOrderRef,sizeof(TThostFtdcOrderRefType));

	strncpy_s(pInputOrder->BrokerID,sizeof(TThostFtdcBrokerIDType),m_pThostFtdcTraderSpiImpl->m_logininfo.BrokerID,sizeof(TThostFtdcBrokerIDType));
	strncpy_s(pInputOrder->InvestorID,sizeof(TThostFtdcInvestorIDType),m_pThostFtdcTraderSpiImpl->m_logininfo.UserID,sizeof(TThostFtdcInvestorIDType));
	strncpy_s(pInputOrder->OrderRef,sizeof(TThostFtdcOrderRefType),m_pThostFtdcTraderSpiImpl->m_logininfo.MaxOrderRef,sizeof(TThostFtdcOrderRefType));
	strncpy_s(pInputOrder->UserID,sizeof(TThostFtdcUserIDType),m_pThostFtdcTraderSpiImpl->m_logininfo.UserID,sizeof(TThostFtdcUserIDType));

	this->m_pTradeUserApi->ReqOrderInsert(pInputOrder,this->m_pThostFtdcTraderSpiImpl->GetRequestId());
	m_AverageMap.insert(iOrderRef,AverageNo);	//存储 报单号与均价单号的对应关系
}
///报单请求
void MainWindow::OnOrderInsert(CThostFtdcInputOrderField *pInputOrder){
	//报单引用
	TThostFtdcOrderRefType NewOrderRef;
	int iOrderRef;

	strncpy_s(NewOrderRef,sizeof(TThostFtdcOrderRefType),m_pThostFtdcTraderSpiImpl->m_logininfo.MaxOrderRef,sizeof(TThostFtdcOrderRefType));
	iOrderRef=atoi(NewOrderRef);
	iOrderRef++;
	itoa(iOrderRef,NewOrderRef,10);
	strncpy_s(m_pThostFtdcTraderSpiImpl->m_logininfo.MaxOrderRef,sizeof(TThostFtdcOrderRefType),NewOrderRef,sizeof(TThostFtdcOrderRefType));

	strncpy_s(pInputOrder->BrokerID,sizeof(TThostFtdcBrokerIDType),m_pThostFtdcTraderSpiImpl->m_logininfo.BrokerID,sizeof(TThostFtdcBrokerIDType));
	strncpy_s(pInputOrder->InvestorID,sizeof(TThostFtdcInvestorIDType),m_pThostFtdcTraderSpiImpl->m_logininfo.UserID,sizeof(TThostFtdcInvestorIDType));
	strncpy_s(pInputOrder->OrderRef,sizeof(TThostFtdcOrderRefType),m_pThostFtdcTraderSpiImpl->m_logininfo.MaxOrderRef,sizeof(TThostFtdcOrderRefType));
	strncpy_s(pInputOrder->UserID,sizeof(TThostFtdcUserIDType),m_pThostFtdcTraderSpiImpl->m_logininfo.UserID,sizeof(TThostFtdcUserIDType));
	//发送报单请求	
	this->m_pTradeUserApi->ReqOrderInsert(pInputOrder,this->m_pThostFtdcTraderSpiImpl->GetRequestId());
}
/////报单录入请求响应
void MainWindow::OnRspOrderInsert(CThostFtdcInputOrderField *pInputOrder, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast){
	if (0 != pRspInfo->ErrorID){
		QString errmsg = "报单录入请求失败。ErrorID："+ QString::number(pRspInfo->ErrorID) + "\n" + QString::fromLocal8Bit(pRspInfo->ErrorMsg).toStdString().c_str();
		QMessageBox::critical(NULL,QString("ERROR"),errmsg);
	}
}
///报单通知
void MainWindow::OnRtnOrder(CThostFtdcOrderField *pOrder){
    if( THOST_FTDC_CC_Immediately == pOrder->ContingentCondition){
        ///立即委托单
		int iOrderRef=atoi(pOrder->OrderRef);
		if(m_CombineMap.contains(iOrderRef)){
			//组合单判断 查询对应的组合单单号
			QString strCombineNO = m_CombineMap[iOrderRef];
            m_tabWidget->setCurrentIndex(3);//显示组合单Tab
			this->maincombineentrustwidget->ShowCombineOrder(strCombineNO,pOrder);//在组合单Tab上显示报单信息
		}else if(m_AverageMap.contains(iOrderRef)){
			//均价单判断 查询对应的均价单单号
			QString strAverageNO = m_AverageMap[iOrderRef];
			this->mainaverageentrustwidget->ShowAverageOrder(strAverageNO,pOrder);//在均价单Tab上显示报单信息
        }else{
            //普通委托单
            this->mainorderwidget->ShowRtnOrder(pOrder);
            m_tabWidget->setCurrentIndex(0);//委托Tab显示
		}			
    }else if(THOST_FTDC_CC_ParkedOrder == pOrder->ContingentCondition){
        /// 预埋单
        m_tabWidget->setCurrentIndex(1);//预埋单Tab显示
    }else{
        ///条件单反馈
        m_tabWidget->setCurrentIndex(2);//条件单Tab显示
		mainconditionwidget->ShowConditionOrder(pOrder);
	}
}
///成交通知
void MainWindow::OnRtnTrade(CThostFtdcTradeField *pTrade){
	//组合单判断 查询对应的批量单单号
	int iOrderRef=atoi(pTrade->OrderRef);
	if(m_CombineMap.contains(iOrderRef)){
		QString strCombineNO = m_CombineMap[iOrderRef];
        m_tabWidget->setCurrentIndex(3);//显示组合单Tab
		this->maincombineentrustwidget->ShowCombineOrder(strCombineNO,pTrade);//在组合单Tab上显示报单信息
    }
    //收到成交通知后 实时查询更新用户持仓信息
    mainholdwidget->QueryButtonClicked();
}

///深度行情通知
void MainWindow::OnDepthMarketData(CThostFtdcDepthMarketDataField *pDepthMarketData){
    QString strInstrumentID = QString(pDepthMarketData->InstrumentID);
    //自选合约
    for(int i = 0; i < m_ContractVector.size(); i++){
        if(0 == strcmp(pDepthMarketData->InstrumentID,m_ContractVector[i].InstrumentID)){
            marketselfwidget->ShowDepthMarketData(pDepthMarketData);
            break;
        }
    }
    //自定义组合合约
    m_CombineSelfMap.insert(QString(pDepthMarketData->InstrumentID),*pDepthMarketData);
    for(int j = 0; j < m_CombineSelfVector.size(); j++){
        MarketComExchInstrument oMarketComExchInstrument = m_CombineSelfVector[j];
        if(oMarketComExchInstrument.m_strLeg1 == strInstrumentID ){
            if(m_CombineSelfMap.contains(oMarketComExchInstrument.m_strLeg2)){
                marketcomexch->ShowDepthMarketData(pDepthMarketData,&m_CombineSelfMap[oMarketComExchInstrument.m_strLeg2]);
            }
        }
        if(oMarketComExchInstrument.m_strLeg2 == strInstrumentID ){
            if(m_CombineSelfMap.contains(oMarketComExchInstrument.m_strLeg1)){
                marketcomexch->ShowDepthMarketData(&m_CombineSelfMap[oMarketComExchInstrument.m_strLeg1],pDepthMarketData);
            }
        }
    }
    //交易所组合行情   CTP接口暂时没有交易所组合行情接口
    //for(int k =0; k < m_CombineExchVector.size(); k++){
       //if(strInstrumentID == m_CombineExchVector[k]){
           //显示交易所组合行情
       //}
    //}
}
